 package com.esp.soccertutor.ui;

import java.util.ArrayList;

import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.esp.soccertutor.R;
import com.esp.soccertutor.ui.bean.BeanCountry;
import com.esp.soccertutor.ui.xmlparser.XMLParser_CommonUse;
import com.esp.soccertutor.ui.xmlparser.XMLParser_Country;
import com.esp.soccertutor.util.Const;
import com.esp.soccertutor.util.Log;
import com.esp.soccertutor.util.Pref;
import com.esp.soccertutor.util.Utils;

public class Login extends Activity implements OnClickListener,OnFocusChangeListener{
	
	public String TAG = Login.class.getCanonicalName();
	
	private Button btn_login,btn_getFree;
	private EditText editText_UserName,editText_Password;
	private EditText editText_FirstName,editText_Email,editText_NewPassword;
	private TextView txtView_Country;
	private ProgressDialog mProgressDialog;
	private ArrayList<BeanCountry> arrylstBeanCountry;
	private String[]strCountry;
	private LinearLayout layout_loginPanel;
	private EditText editTextCustom;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		btn_login = (Button)findViewById(R.id.btn_login);
		btn_getFree = (Button)findViewById(R.id.btn_getFree);
		btn_getFree.setOnClickListener(this);
		btn_login.setOnClickListener(this);
		
		editText_UserName = (EditText)findViewById(R.id.editText_UserName);
		editText_UserName.setOnFocusChangeListener(this);
		editText_Password = (EditText)findViewById(R.id.editText_Password);
		editText_Password.setOnFocusChangeListener(this);
		
		editText_FirstName = (EditText)findViewById(R.id.editText_FirstName);
		editText_FirstName.setOnFocusChangeListener(this);
		editText_Email = (EditText)findViewById(R.id.editText_Email);
		editText_Email.setOnFocusChangeListener(this);
		editText_NewPassword = (EditText)findViewById(R.id.editText_NewPassword);
		editText_NewPassword.setOnFocusChangeListener(this);
		
		txtView_Country = (TextView)findViewById(R.id.txtView_Country);
		
		mProgressDialog = new ProgressDialog(Login.this);
		mProgressDialog.setMessage(getString(R.string.ProgressMessage));
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgressDialog.setCancelable(false);
		
		txtView_Country.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				AsyncTask<Void, Void, Integer> mCountryList = new AsyncTask<Void, Void, Integer>() {
					
					@Override
					protected void onPreExecute() {
						super.onPreExecute();
						mProgressDialog.show();
					}
					@Override
					protected Integer doInBackground(Void... params) {
						int Result = 0;
						if(arrylstBeanCountry != null){
							
							strCountry = new String[arrylstBeanCountry.size()];
							strCountry = Utils.arrListToArray(arrylstBeanCountry);
							
						}else{
							Result = -1;
						}
							
						return Result;
					}
					@Override
					protected void onPostExecute(Integer result) {
						super.onPostExecute(result);
						mProgressDialog.dismiss();
						if(result == 0){
							
							AlertDialog alertDays = new AlertDialog.Builder(Login.this)
							.setSingleChoiceItems(
									strCountry,
									Integer.parseInt(Pref.getValue(
											Const.COUNTRY_ID, "0")),
									new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,
												int item) {
											Pref.setValue(Const.COUNTRY_ID,item+"");
											dialog.dismiss();
										}
									}).create();
							
							alertDays.setTitle("Country List");
							alertDays.show();
						}
						
					}
				};
				mCountryList.execute();
				
			}
		});
	}
	

	public void onFocusChange(View v, boolean hasFocus) {
		if(hasFocus)
			editTextCustom = (EditText)v;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		AsyncTask<Void, Void, Integer> mCountryTask = new AsyncTask<Void, Void, Integer>() {
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				mProgressDialog.show();
			}
			@Override
			protected Integer doInBackground(Void... params) {
				int Result = 0;
				try
				{
					//TODO call over server
					XMLParser_Country mParser = new XMLParser_Country(Const.BOOK_URL);
					if(XMLParser_Country.STATUS_CODE == 200){
						
						//TODO We Reach Here if XML is Available
						arrylstBeanCountry = new ArrayList<BeanCountry>();
						arrylstBeanCountry = mParser.getCountry(XMLParser_Country.GetDocument());
						
					}else if(XMLParser_Country.STATUS_CODE == 400){
						Result = 400;
					}else if(XMLParser_Country.STATUS_CODE == 500){
						Result = 500;
					}
					
				}catch (Exception e) {
					e.printStackTrace();
				}
				return Result;
			}
			@Override
			protected void onPostExecute(Integer result) {
				super.onPostExecute(result);
				mProgressDialog.dismiss();
				if(result == 0){
				}
			}
		};
		mCountryTask.execute();
		
		//TODO THIS IS HERE FOR KEYBOARD HIDDING
		layout_loginPanel = (LinearLayout)findViewById(R.id.layout_loginPanel);
		layout_loginPanel.requestFocus();
		layout_loginPanel.setOnTouchListener(new OnTouchListener() {
			
			public boolean onTouch(View v, MotionEvent event) {
				
				if(v == layout_loginPanel)
				{
					if(editTextCustom!= null){
						
						InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(editTextCustom.getWindowToken(), 0);
						return true;
					}
					
				}
					return false;
			}
		});
		
		
	}
	@Override
	protected void onPause() {
		super.onPause();
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.btn_login:
			
			if(!editText_UserName.getText().toString().equals("") && !editText_Password.getText().toString().equals(""))
			{
				AsyncTask<Void, Void,Integer> appLoginProcess = new AsyncTask<Void, Void, Integer>() {

					@Override
					protected void onPreExecute() {
						super.onPreExecute();
						mProgressDialog.show();
					}
					@Override
					protected Integer doInBackground(Void... params) {
						int Result = 0;
						try
						{
							//TODO CHECK OVER SERVER
							ArrayList<BasicNameValuePair> mNameValuePair = new ArrayList<BasicNameValuePair>();
							mNameValuePair.add(new BasicNameValuePair("UserName",editText_UserName.getText().toString()));
							mNameValuePair.add(new BasicNameValuePair("Password", editText_Password.getText().toString()));
							mNameValuePair.add(new BasicNameValuePair("DeviceType","100002"));
							mNameValuePair.add(new BasicNameValuePair("DeviceUDID",Utils.getDeviceID(Login.this)));
							
							XMLParser_CommonUse mCommonUse = new XMLParser_CommonUse(Const.BOOK_URL,mNameValuePair);
							
							if(XMLParser_CommonUse.STATUS_CODE == 200){
								//XML Available 
								mCommonUse.getResponse(XMLParser_CommonUse.GetDocument(),1);
								if(XMLParser_CommonUse.RESPONSE_CODE == 1){
									
									Log.print(TAG,"User Name : " + mCommonUse.getUserName());
									Log.print(TAG,"User ID : " + mCommonUse.getUserID());
									Log.print(TAG,"User First : " + mCommonUse.getUserFirstName());
									Log.print(TAG,"User Country : " + mCommonUse.getUCountry());
									
								}
							}else if(XMLParser_CommonUse.STATUS_CODE == 400){
								//No XML Available
								Result = 400;
								
							}else if(XMLParser_CommonUse.STATUS_CODE == 500){
								//Internal Error
								Result = 500;
							}
							
						}catch (Exception e) {
							e.printStackTrace();
							Result = 500;
							
						}
						return Result;
					}
					@Override
					protected void onPostExecute(Integer result) {
						super.onPostExecute(result);
						mProgressDialog.dismiss();
						if(result == 0){
							
							Intent mPurchaseIntent = new Intent(Login.this,MyPurchaseActivity.class);
							mPurchaseIntent.putExtra(Const.PURCHASE, Const.INT_PURCHASE);
							mPurchaseIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(mPurchaseIntent);
						}
					}
				};
				appLoginProcess.execute();
				
				
			}else{
				Toast.makeText(Login.this,"Please fill details",Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.btn_getFree:
			if(!editText_FirstName.getText().toString().equals("") && !editText_Email.getText().toString().equals("") && !editText_NewPassword.getText().toString().equals("") && !txtView_Country.getText().toString().equals("")){
				
				//TODO check Email Address
				if(Utils.checkEmail(editText_Email.getText().toString())){
					
					Intent mPurchaseIntent = new Intent(Login.this,MyPurchaseActivity.class);
					mPurchaseIntent.putExtra(Const.PURCHASE, Const.INT_PURCHASE);
					mPurchaseIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(mPurchaseIntent);
				}
				
			}else{
				
				Toast.makeText(Login.this,"Please fill details",Toast.LENGTH_LONG).show();
			}
			break;

		default:
			break;
		}
	}

}
